package cn.edu.sdjzu.xg.bysj.service;
//201902104061徐中堂
import cn.edu.sdjzu.xg.bysj.dao.ActorDao;
import cn.edu.sdjzu.xg.bysj.domain.authority.Actor;
import cn.edu.sdjzu.xg.bysj.domain.authority.ActorAssRole;
import cn.edu.sdjzu.xg.bysj.domain.authority.Role;
import util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.TreeSet;

public final class ActorService {
    //获取ActorDao实例
    private static final ActorDao actorDao = ActorDao.getInstance();
    //新建ActorService对象
    private static final ActorService actorService = new ActorService();
    //获取ActorService对象
    public static ActorService getInstance() {
        return actorService;
    }

    /**
     * 获得Actor 对应id对应的对象
     *
     * @param id
     * @return
     * @throws SQLException
     */
    public Actor find(Integer id) throws SQLException {
        //获取数据库连接
        Connection connection = JdbcHelper.getConn();
        //将自动提交设为false,开始事务
        connection.setAutoCommit(false);
        Actor actor = null;
        try {
            actor = actorDao.find(id, connection);
            //提交事务
            connection.commit();
        }
        catch (SQLException e) {
            //回滚事务中所有操作
            connection.rollback();
        }
        finally {
            //将自动提交设置为true，结束事务
            connection.setAutoCommit(true);
            //释放连接
            JdbcHelper.close(connection);
        }
        return actor;
    }

    /**
     * 获得参数Actor对象应对的所有Role，后者又关联着Resource
     *
     * @param actor
     * @return
     * @throws SQLException
     */
    public Collection<Role> getRoles(Actor actor) throws SQLException {
        Collection<ActorAssRole> actorAssRoles = ActorAssRoleService.getInstance().findAll(actor);
        System.out.println(actorAssRoles);
        Collection<Role> roles = new TreeSet<Role>();
        for (ActorAssRole actorAssRole : actorAssRoles) {
            roles.add(actorAssRole.getRole());
        }
        return roles;
    }

}
